import { createWebHashHistory, createRouter } from 'vue-router'
import { useUserStore } from '@/store/user'

// 所有需要登录的子路由
const authChildren = [
    { path: '', component: () => import('@/views/home/index.vue') },
    { path: 'user', component: () => import('@/views/user/index.vue') },
    { path: 'post', component: () => import('@/views/post/index.vue') },
    { path: 'addPost', component: () => import('@/views/post/addPost.vue') },
    { path: 'updatePost', component: () => import('@/views/post/Update.vue') },
    { path: 'add', component: () => import('@/views/user/components/add.vue') },
    { path: 'update', component: () => import('@/views/user/components/update.vue') },
    { path: 'my', component: () => import('@/views/my/index.vue') },
].map(route => ({
    ...route,
    meta: { requiresAuth: true }
}))

const routes = [
    {
        path: '/',
        component: () => import('@/layout/index.vue'),
        children: authChildren
    },
    { path: '/login', component: () => import('@/views/login/index.vue') },
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: () => import('@/views/404/404.vue') },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem('token')
    console.log('【路由守卫触发】 to:', to.path, 'token:', token)

    if (to.meta.requiresAuth && !token) {
        console.log('未登录，跳转登录页')
        next('/login')
    } else if (to.path === '/login' && token) {
        console.log('已登录，跳转首页')
        next('/')
    } else {
        next()
    }
})

export default router
